﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.LiveFX.Client;
using Microsoft.LiveFX.ResourceModel;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;

namespace LiveFrameworkExplorer.Plugins
{
    public class AddInivitationPlugin : IPlugin, IPluginItem
    {
        private ILFEBase _lfeBase = null;

        #region IPlugin Members

        public void Init(ILFEBase lfeBase)
        {
            _lfeBase = lfeBase;
        }

        public List<Type> GetTypes()
        {
            return new List<Type>() {
                typeof(LiveItemCollection<Member, MemberResource>),
                typeof(MeshObject)
            };
        }

        public string GetMenuItemLabel()
        {
            return "Invite a new member";
        }

        public Image GetMenuItemImage()
        {
            return LiveFrameworkExplorer.Properties.Resources.contact;
        }

        public bool CheckItem<TMeshItem, TResource>(object item)
            where TMeshItem : Microsoft.LiveFX.Client.LiveItem<TResource>, new()
            where TResource : Microsoft.LiveFX.ResourceModel.Resource, new()
        {
            return true;
        }

        public void OpenPlugin<TMeshItem, TResource>(object item, object parentItem)
            where TMeshItem : Microsoft.LiveFX.Client.LiveItem<TResource>, new()
            where TResource : Microsoft.LiveFX.ResourceModel.Resource, new()
        {
            var meshObject = (item is MeshObject) ?
                item as MeshObject : parentItem as MeshObject;
            if (meshObject != null)
            {
                var contactsList = _lfeBase.GetLiveOperatingEnvironment().Contacts.Entries
                    .Select<Contact, string>(c => c.Resource.WindowsLiveId).Where<string>(s => !string.IsNullOrEmpty(s));
                var invit = new dlgAddInvitation(contactsList);
                if (invit.ShowDialog() == DialogResult.OK)
                {
                    Member member = new Member(invit.ContactLiveID, invit.RoleType.Value, invit.IsOwner);
                    meshObject.Members.Add(ref member);
                    meshObject.UpdateCompleted +=
                        (object sender2, AsyncCompletedEventArgs e2) =>
                        {
                            MessageBox.Show(invit.ContactLiveID + " is invited !");
                        };
                    // Update the mesh object
                    meshObject.UpdateAsync(null);
                }
            }
        }

        #endregion
    }
}
